package cn.kgc.javaweb.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.javaweb.dao.UserDao;
import cn.kgc.javaweb.dao.impl.UserDaoImpl;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.form.UserLoginForm;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.vo.UserVO;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/15
 * @Description:
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();
    @Override
    public HashMap<String, Object> register(String username, String password) {

        HashMap<String, Object> map = new HashMap<>();
        //1.根据用户名查询用户信息  判定用户是否已被注册
        User user = userDao.selectByUserName(username);
        if(user==null){
            // 2.将用户信息写入数据库  持久化
            Integer line =  userDao.registerUser(username, SecureUtil.md5(password));
            if(line==1){
                map.put("code",0);
                map.put("msg","注册成功");
            }else {
                map.put("code",500);
                map.put("msg","注册失败");
            }
        }else {
            map.put("code",500);
            map.put("msg","用户名已存在");
        }

        return map;
    }
    // 登录业务逻辑
    @Override
    public HashMap<String, Object> login(UserLoginForm userLoginForm, HttpServletRequest req, HttpServletResponse resp) {

        HashMap<String, Object> map = new HashMap<>();
        //1. 判定验证码
        String captcha = userLoginForm.getCaptcha();
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        if(code.equals(captcha)){  //  验证正确
            //判定用户名是否正确
            User user = userDao.selectByUserName(userLoginForm.getUsername());
            if(user!=null){  // 用户名存在
                // 判定密码
                String password = SecureUtil.md5(userLoginForm.getPassword());
                String md5Pwd = user.getPassword();
                if(md5Pwd.equals(password)){  // 成功
                    // 判定用户是否勾选记住我
                    String remember = userLoginForm.getRemember();
                    if("true".equals(remember)){
                        Cookie usernameCookie = new Cookie("username", userLoginForm.getUsername());
                        Cookie passwordCookie = new Cookie("password", userLoginForm.getPassword());
                        Cookie rememberCookie = new Cookie("remember", userLoginForm.getRemember());
                        // 设置cookie的存活时间
                        usernameCookie.setMaxAge(60*5);
                        passwordCookie.setMaxAge(60*5);
                        rememberCookie.setMaxAge(60*5);
                        // 将cookie绑定在response中
                        resp.addCookie(usernameCookie);
                        resp.addCookie(passwordCookie);
                        resp.addCookie(rememberCookie);
                    }else{   //立即删除浏览器中缓存cookie
                        Cookie usernameCookie = new Cookie("username", "");
                        Cookie passwordCookie = new Cookie("password", "");
                        Cookie rememberCookie = new Cookie("remember", "");
                        // 设置cookie的存活时间
                        usernameCookie.setMaxAge(0);
                        passwordCookie.setMaxAge(0);
                        rememberCookie.setMaxAge(0);
                        // 将cookie绑定在response中
                        resp.addCookie(usernameCookie);
                        resp.addCookie(passwordCookie);
                        resp.addCookie(rememberCookie);
                    }


                    //将用户信息 保存在session中 用户数据共享
                    session.setAttribute("user",user);
                    map.put("code",0);
                    map.put("msg","登录成功");
                }else {
                    map.put("code",500);
                    map.put("msg","密码错误");
                }

            }else { // 用户名错误
                map.put("code",500);
                map.put("msg","用户名不存在");
            }

        }else {  // 验证码错误
            map.put("code",500);
            map.put("msg","验证码错误");
        }


        return map;
    }

    @Override
    public User getUserByUserName(String username) {
        return  userDao.selectByUserName(username);
    }

    @Override
    public HashMap<String, Object> updateUser(User user) {
        HashMap<String, Object> map = new HashMap<>();
        Integer  line =  userDao.updateUser(user);
        if(line==1){
            map.put("code",0);
            map.put("msg","个人资料更新成功");
        }else {
            map.put("code",500);
            map.put("msg","个人资料更新失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updatePwd(String username, String newPassword, String oldPassword) {

        HashMap<String, Object> map = new HashMap<>();

        // 1.判定原始密码是否正确
        User user = userDao.selectByUserName(username);
        String password = user.getPassword();
        if(password.equals(SecureUtil.md5(oldPassword))){
            try {
                userDao.updatePwd(username,newPassword);
                map.put("code",0);
                map.put("msg","密码修改成功");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                map.put("code",500);
                map.put("msg","密码修改失败");
            }
        }else {
            map.put("code",500);
            map.put("msg","原始密码错误");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> getList(Integer page, Integer limit) {

        // 1. 返回数据格式  {code:0,msg:'',count:100,data:[]}
        HashMap<String, Object> map = new HashMap<>();

        /**
         * 2.查询当前页数据  data   page = 5  limit=10
         *  select *  from user  limit start,limit
         *                                0,5
         *                                5,5
         *                               10,5
         *                  (page-1)*limit , limit
         */

        Integer start = (page-1)*limit;
        try {
            List<UserVO>  userVOS = userDao.getList(start,limit);
            // 3.查询数据的总条数  count
            Long total = userDao.getTotal();
            map.put("code",0);
            map.put("msg","查询成功");
            map.put("data",userVOS);
            map.put("count", total);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            map.put("code",500);
            map.put("msg","查询失败");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> addUser(User user) {

        HashMap<String, Object> map = new HashMap<>();
        //1.判定用户名是否能已存在
        User usr = userDao.selectByUserName(user.getUsername());
        if(usr==null){
            try {
                userDao.addUser(user);
                map.put("code",0);
                map.put("msg","用户添加成功");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                map.put("code",500);
                map.put("msg","用户添加失败");
            }
        }else {
            map.put("code",500);
            map.put("msg","用户名已存在");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updateUserByRoot(User user) {

        HashMap<String, Object> map = new HashMap<>();

        try {
            userDao.updateUserByRoot(user);
            map.put("code",0);
            map.put("msg","用户信息修改成功");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            map.put("code",500);
            map.put("msg","用户信息修改失败");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> deleteBatch(String[] ids) {
        HashMap<String, Object> map = new HashMap<>();

        try {
            userDao.deleteBatch(ids);
            map.put("code",0);
            map.put("msg","删除成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","删除失败");
        }
        return map;
    }
}
